# -*- coding: utf-8 -*-

#    OriginDB
#    Copyright (C) 2009  Jason Power <power.jg@gmail.com>
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License along
#    with this program; if not, write to the Free Software Foundation, Inc.,
#    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

from PyQt4 import QtCore, QtGui
from ui_referenceEdit import Ui_ReferenceEditFrame

class ReferenceEdit(QtGui.QFrame):
	def __init__(self, controller, referenceClass, mode='New'):
		QtGui.QFrame.__init__(self)

		self.controller = controller

		self.referenceClass = referenceClass
		self.reference = None

        # Set up the user interface from Designer.
		self.ui = Ui_ReferenceEditFrame()
		self.ui.setupUi(self)

		self.setMode(mode)

		self.setReadonly(not self.controller.userLoggedIn())

		self.connect(self.ui.addPushButton, QtCore.SIGNAL("clicked()"), self.insertReference)
		self.connect(self.ui.updatePushButton, QtCore.SIGNAL("clicked()"), self.updateReferenceAction)
		self.connect(self.ui.clearPushButton, QtCore.SIGNAL("clicked()"), self.clear)
		self.connect(self.ui.importPushButton, QtCore.SIGNAL("clicked()"), self.controller.importReferenceAction)
		self.connect(self.ui.searchPushButton, QtCore.SIGNAL("clicked()"), self.search)


	def insertReference(self):
		self.reference = self.referenceClass()

		self.updateReference()

		self.reference.insert()

		if self.mode.find("Dialog") != -1:
			self.controller.addToReaction(self.reference, "Reference")

		self.msgDialog = QtGui.QMessageBox(QtGui.QMessageBox.Information, "Reference Added", "Reference added successfully", QtGui.QMessageBox.Ok)
		self.msgDialog.show()


	def initFocus(self):
		self.ui.nameLineEdit.setFocus(QtCore.Qt.OtherFocusReason)


	def updateReference(self):

		self.reference.title = str(self.ui.nameLineEdit.text()).strip()
		self.reference.year = self.ui.yearSpinBox.value()
		if self.reference.year == 1800:
			self.reference.year = None
		self.reference.author_name = str(self.ui.authorLineEdit.text())
		self.reference.source = str(self.ui.journalLineEdit.text()).upper().strip()
		self.reference.volume = self.ui.volumeSpinBox.value()
		self.reference.issue = self.ui.issueSpinBox.value()
		self.reference.pageStart = self.ui.pageStartSpinBox.value()
		self.reference.pageEnd = self.ui.pageEndSpinBox.value()
		self.reference.abstract = str(self.ui.abstractTextEdit.toPlainText())

		self.reference.forceUpdate()

	def updateReferenceAction(self):
		self.updateReference()

		self.msgDialog = QtGui.QMessageBox(QtGui.QMessageBox.Information, "Reference Updated", "Reference updated successfully", QtGui.QMessageBox.Ok)
		self.msgDialog.show()

	def search(self):
		self.reference = self.referenceClass()
		self.updateReference()

		if self.mode.find("Dialog") == -1:
			self.controller.searchReference(self.reference)
		else:
			self.controller.searchReferenceFromDialog(self.reference)


	def clear(self):
		self.ui.nameLineEdit.clear()
		self.ui.yearSpinBox.setValue(1800)
		self.ui.authorLineEdit.clear()
		self.ui.journalLineEdit.clear()
		self.ui.volumeSpinBox.setValue(0)
		self.ui.issueSpinBox.setValue(0)
		self.ui.pageStartSpinBox.setValue(0)
		self.ui.pageEndSpinBox.setValue(0)
		self.ui.abstractTextEdit.clear()

		self.reference = None

	def setCurrentReference(self, reference):
		self.reference = reference
		self.updateFields()

		if not self.readonly:
			self.ui.updatePushButton.show()

	def setReadonly(self, readonly):
		self.readonly = readonly

		#self.ui.nameLineEdit.setReadOnly(readonly)
		#self.ui.yearSpinBox.setReadOnly(readonly)
		#self.ui.authorLineEdit.setReadOnly(readonly)
		#self.ui.journalLineEdit.setReadOnly(readonly)
		#self.ui.volumeSpinBox.setReadOnly(readonly)
		#self.ui.pagesLineEdit.setReadOnly(readonly)

		self.ui.addPushButton.setEnabled(not readonly)
		
		if not self.readonly and self.reference and self.reference.key:
			self.ui.updatePushButton.show()
		else:
			self.ui.updatePushButton.hide()

	def setMode(self, mode):
		self.mode = mode
		if self.mode.find("New") != -1:
			self.ui.addPushButton.show()
			self.ui.updatePushButton.hide()
			self.ui.editLine.hide()
			self.ui.searchPushButton.hide()
		elif mode == "Search":
			self.ui.addPushButton.hide()
			self.ui.updatePushButton.hide()
			self.ui.editLine.hide()
			self.ui.searchPushButton.show()
		elif mode == "Search Dialog":
			self.ui.addPushButton.hide()
			self.ui.updatePushButton.hide()
			self.ui.editLine.hide()
			self.ui.searchPushButton.show()

	def updateFields(self):
		self.ui.nameLineEdit.setText(self.reference.title)
		self.ui.yearSpinBox.setValue(int(self.reference.year))
		self.ui.authorLineEdit.setText(self.reference.author_name)
		if self.reference.source:
			self.ui.journalLineEdit.setText(self.reference.source)
		self.ui.volumeSpinBox.setValue(int(self.reference.volume))
		self.ui.issueSpinBox.setValue(int(self.reference.issue))
		self.ui.pageStartSpinBox.setValue(int(self.reference.pageStart))
		self.ui.pageEndSpinBox.setValue(int(self.reference.pageEnd))
		if self.reference.abstract:
			self.ui.abstractTextEdit.setPlainText(self.reference.abstract)

	def importReference(self):
		dialog = QtGui.QFileDialog(self, "Choose file to import", "", "")
		dialog.setAcceptMode(QtGui.QFileDialog.AcceptOpen)
		dialog.setFileMode(QtGui.QFileDialog.ExistingFile)
		filename = ''
		if dialog.exec_():
			for name in dialog.selectedFiles():
				filename = name
		if not filename:
			return

		f = file(filename)
		line = f.next().strip()
		if filename.endswith(".ris") or not line:
			self.reference = self.importACS(f)
		elif line == "FN ISI Export Format":
			self.reference = self.importWoS(f)
		elif line.find("Journal Article") != -1:
			if line.find("Reference Type") != -1:
				self.reference = self.importEndNote(f)
			elif line.find("%0") != -1:
				self.reference = self.importEndNoteWeb(f)
		else:
			dialog = QtGui.QMessageBox(QtGui.QMessageBox.Critical, "File Error", "File is not of the right type.\n Please only import 'ris' files (like from ACS), text files from ISI (Web of Science), Exported EndNote files as All fields, or text files exported from EndNote online.", QtGui.QMessageBox.Ok)
			dialog.setModal(True)
			dialog.exec_()
			return
			
		self.updateFields()

	def importACS(self, f):
		reference = self.referenceClass()
		print "importing from ACS"
		for line in f:
			if line[0] == "\n":
				continue
			if line[0:2] == "AU":
				reference.author_name += line[6:-1]+"; "
			elif line[0:2] == "T1":
				reference.title = line[6:-1]
			elif line[0:2] == "JO":
				reference.source = line[6:-1]
			elif line[0:2] == "N2":
				reference.abstract = line[6:-1]
			elif line[0:2] == "PY":
				try:
					reference.year = int(line[6:line.find("/")])
				except ValueError:
					pass
			elif line[0:2] == "VL":
				try:
					reference.volume = int(line[6:])
				except ValueError:
					pass
			elif line[0:2] == "IS":
				try:
					reference.issue = int(line[6:])
				except ValueError:
					pass
			elif line[0:2] == "SP":
				try:
					reference.pageStart = int(line[6:])
				except ValueError:
					pass
			elif line[0:2] == "EP":
				try:
					reference.pageEnd = int(line[6:])
				except ValueError:
						pass
			elif line[0:2] == "ER":
				break

		print reference.author_name
		print reference.title
		print reference.source
		print reference.abstract
		print reference.year
		print reference.volume
		print reference.issue
		print reference.pageStart
		print reference.pageEnd

		return reference

	def importWoS(self, f):
		reference = self.referenceClass()
		print "importing from WoS"
		working = None
		for line in f:
			if line[0:2] != "  ":
				working = None
			if line[0:2] == "AU":
				working = "reference.author_name"
			elif line[0:2] == "AF":
				reference.author_name = ""
				working = "reference.author_name"
			elif line[0:2] == "TI":
				working = "reference.title"
			elif line[0:2] == "SO":
				working = "reference.source"
			elif line[0:2] == "AB":
				working = "reference.abstract"
			elif line[0:2] == "PY":
				try:
					reference.year = int(line[3:])
				except ValueError:
					pass
			elif line[0:2] == "VL":
				try:
					reference.volume = int(line[3:])
				except ValueError:
					pass
			elif line[0:2] == "IS":
				try:
					reference.issue = int(line[3:])
				except ValueError:
					pass
			elif line[0:2] == "BP":
				try:
					reference.pageStart = int(line[3:])
				except ValueError:
					pass
			elif line[0:2] == "EP":
				if line.find('&') != -1:
					reference.pageEnd = 0
				else:
					try:
						reference.pageEnd = int(line[3:])
					except ValueError:
						pass
			elif line[0:2] == "ER":
				break

			if working:
				exec(working + " += line[3:-1]+' '")
				if working == "reference.author_name":
					reference.author_name += "; "

		print reference.author_name
		print reference.title
		print reference.source
		print reference.abstract
		print reference.year
		print reference.volume
		print reference.issue
		print reference.pageStart
		print reference.pageEnd
		
		return reference
		
	def importEndNoteWeb(self, f):
		reference = self.referenceClass()
		print "importing from end note web"
		for line in f:
			if line[0:2] == "%A":
				reference.author_name += line[3:].strip('\n')+'; '
			elif line[0:2] == "%T":
				reference.title = line[3:]
			elif line[0:2] == "%J":
				reference.source = line[3:]
			elif line[0:2] == "%X":
				reference.abstract = line[3:]
			elif line[0:2] == "%D":
				try:
					reference.year = int(line[3:])
				except ValueError:
					pass
			elif line[0:2] == "%V":
				try:
					reference.volume = int(line[3:])
				except ValueError:
					pass
			elif line[0:2] == "%N":
				try:
					reference.issue = int(line[3:])
				except ValueError:
					pass
			elif line[0:2] == "%P":
				try:
					reference.pageStart = int(line[3:line.find('-')])
				except ValueError:
					pass
				try:
					reference.pageEnd = int(line[line.find('-')+1:])
				except ValueError:
					pass

		print reference.author_name
		print reference.title
		print reference.source
		print reference.abstract
		print reference.year
		print reference.volume
		print reference.issue
		print reference.pageStart
		print reference.pageEnd
		
		return reference
	
	def importEndNote(self, f):
		reference = self.referenceClass()
		print "importing from end note"
		for line in f:
			if line.find("Author:") != -1:
				reference.author_name = line[8:].replace(',', ';').replace(' and', ';')
			elif line.find("Title:") != -1 and line.find("Short Title:") == -1:
				reference.title = line[7:]
			elif line.find("Journal:") != -1:
				reference.source = line[9:]
			elif line.find("Abstract:") != -1:
				reference.abstract = line[10:]
			elif line.find("Year:") != -1:
				try:
					reference.year = int(line[6:])
				except ValueError:
					pass
			elif line.find("Volume:") != -1:
				try:
					reference.volume = int(line[8:])
				except ValueError:
					pass
			elif line.find("Issue:") != -1:
				try:
					reference.issue = int(line[7:])
				except ValueError:
					pass
			elif line.find("Pages:") != -1:
				try:
					reference.pageStart = int(line[7:line.find('-')])
				except ValueError:
					pass
				try:
					reference.pageEnd = int(line[line.find('-')+1:])
				except ValueError:
					pass

		print reference.author_name
		print reference.title
		print reference.source
		print reference.abstract
		print reference.year
		print reference.volume
		print reference.issue
		print reference.pageStart
		print reference.pageEnd
		
		return reference
